const express = require('express')
const Router = express.Router()
const query = require('./db')
const multer = require('multer')
const path = require('path')

// 设置上传文件的配置
let storage = multer.diskStorage({
    // 上传文件保存目录，无则自动创建
    // 要放到后端的static文件夹中
    destination: path.join(__dirname, '../static/images'),
    // 格式化文件名与后缀名
    filename: (req, file, cb) => {
        // req请求对象
        // file 文件
        // cb 回调函数，用于确认文件名
        // file.originalname 上传的原文件的名称加上后缀的
        // file.fieldname formdata数据中存放文件的属性 avatar
        let ext = path.extname(file.originalname)
        let { banner_id } = req.body
        // cb(null, file.fieldname + '-' + banner_id + ext);
        cb(null, `${file.fieldname}${banner_id}${ext}`)
    }
})
// 使用配置
let upload = multer({ storage })

module.exports = Router

/**
 * 获取banner
 */
Router.get('/getBanner', async (req, res) => {
    try {
        let data = await query("select * from banner")
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '获取banner失败'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取banner成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


/**
 * 修改banner_text
 */
Router.post('/updateBannerText', async (req, res) => {
    try {
        let { bannerList } = req.body
        for (const item of bannerList) {
            await query(`update banner set banner_text='${item.banner_text}' where banner_id=${item.banner_id}`)
        }
        res.send({
            code: 200,
            msg: '修改banner描述成功'
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


/**
 * 修改banner_path
 */
Router.post('/updateBannerPhoto', upload.single('banner'), async (req, res) => {
    try {
        let photo = req.file
        let { banner_id } = req.body
        let banner_path = `${process.env.BASE_URL}/images/${photo.filename}`
        console.log(photo, banner_id);
        await query(`update banner set banner_path='${banner_path}' where banner_id=${banner_id}`)
        res.send({
            code: 200,
            msg: '修改banner图片成功'
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})